package com.atguigu.eduservice.controller;


import com.atguigu.commonutils.Result;
import com.atguigu.eduservice.client.VodClientService;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.service.EduVideoService;
import com.atguigu.servicebase.exception.GuliException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.*;


/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2020-08-30
 *
 * 小节控制器
 */
@RestController
@RequestMapping("/eduservice/video")
@Slf4j
public class EduVideoController {

    @Resource
    private EduVideoService videoService;
    @Resource
    private VodClientService vodClientService;

    //添加小节
    @PostMapping("/addVideo")
    public Result addVideo(@RequestBody EduVideo eduVideo) {
        videoService.save(eduVideo);
        return Result.ok();
    }

    //根据id查询小节
    @GetMapping("/getVideoInfoById/{videoId}")
    public Result getVideoInfoById(@PathVariable String videoId) {
        EduVideo video = videoService.getById(videoId);
        return Result.ok().data("video",video);
    }


    //修改小节
    @PostMapping("/updateVideo")
    public Result updateVideo(@RequestBody EduVideo eduVideo) {
        boolean update = videoService.updateById(eduVideo);
        log.info("更新的数据: => {}, 布尔值: =>{}",eduVideo,update);
        return Result.ok();
    }

    //删除小节
    //TODO：这个方法后面需要完善，删除小节的时候删除章节
    @DeleteMapping("/{id}")
    public Result deleteVideo(@PathVariable String id) throws FileNotFoundException {

        //根据小节id查询出视频的id，然后根据feign调用接口删除视频
        EduVideo video = videoService.getById(id);
        String videoSourceId = video.getVideoSourceId(); //获取视频id
        //判断小节里面是否有视频id
        if (!StringUtils.isEmpty(videoSourceId)) {
            //根据id删除视频
            Result remove = vodClientService.remove(videoSourceId);
            log.info("触发消息: => {}",remove);
            if (remove.getCode() == 201) {
                throw new GuliException(201,"删除视频失败，触发熔断器。。。");
            }
        }
        //根据id删除小节，先删除视频
        videoService.removeById(id);
        return Result.ok();
    }
}

